package com.controller;

import com.alibaba.fastjson.JSONArray;
import com.entity.Book;
import com.entity.Category;
import com.service.IBookService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PipedWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/12.
 */
@RequestMapping("book")
@Controller
public class BookController {
    @Resource
    private IBookService bookService;
    @Value("${imagePath}")
    private String imagePath;

    /**
     * 展示书籍信息
     *
     * @return
     */
    @RequestMapping("list")
    public String list(HttpServletRequest request, ModelMap modelMap) {
        String subCategoryName = request.getParameter("subCategoryName");
        System.out.println("imagePath = " + imagePath);
        modelMap.addAttribute("imagePath", imagePath);
        //位-1时，是首次访问主页
        if ("-1".equals(subCategoryName)) {
            Map min = bookService.getMinCategory();
            List<Book> books = bookService.getBookInfoBySubCategoryName(min.get("sub_category_name").toString());
            System.out.println("books = " + books);
            modelMap.addAttribute("books", books);
        } else {
            List<Book> books = bookService.getBookInfoBySubCategoryName(subCategoryName);
            modelMap.addAttribute("books", books);
        }
        return "bookList";
    }

    /**
     * 展示书籍的子分类
     */
    @RequestMapping("subCategory")
//    @ResponseBody
    public void listSubCategory(HttpServletRequest request, HttpServletResponse response) {
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/text;charset=UTF-8");
//        request.setAttribute("reeee", "ddddddddddddddddd");
        String subCategoryName = request.getParameter("subCategory");
        System.out.println("subCategoryName = " + subCategoryName);
        List<Category> categories = bookService.getSubCategory(subCategoryName);
//        JSONObject obj = new JSONObject().;
        String cate = JSONArray.toJSON(categories).toString();
        System.out.println("category=" + cate);
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.print(cate);
        } catch (Exception e) {
            System.out.println("错误！");
        } finally {
            if (null != pw) {
                pw.close();
            }
        }
//        return cate;
    }
}
